﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace QServices;



public class QNetWork
{
	public static List<string> GetLocalIPAddress()
	{
		var res = new List<string>();
		var host = Dns.GetHostEntry(Dns.GetHostName());
		foreach (var ip in host.AddressList)
		{
			if (ip.AddressFamily == AddressFamily.InterNetwork)
			{
				var ipStr = ip.ToString();
				if (!ipStr.Contains("127.0.0.1"))
				{
					res.Add(ipStr);
				}
			}
		}
		return res;
	}

	public static bool IsLocalNetworkAvailable()
	{
		var ips = GetLocalIPAddress();
		foreach (var ip in ips)
		{
			var res = PingHost(ip);
			if (res) return true;
		}
		return false;
	}
	private static bool PingHost(string nameOrAddress)
	{
		Ping pingSender = new Ping();
		PingOptions options = new PingOptions();

		// Use the default Ttl value which is 128,
		// but change the fragmentation behavior.
		options.DontFragment = true;

		// Create a buffer of 32 bytes of data to be transmitted.
		string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
		byte[] buffer = System.Text.Encoding.ASCII.GetBytes(data);
		int timeout = 120; // Timeout in milliseconds (120 seconds)

		try
		{
			PingReply reply = pingSender.Send(nameOrAddress, timeout, buffer, options);
			if (reply.Status == IPStatus.Success)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		catch (Exception)
		{
			// Exception can be thrown if the host is unreachable or if the host does not exist.
			return false;
		}
	}

	public static bool IsInternetAvailable()
	{
		// 使用常用的互联网地址来测试外网连接，如Google的公共DNS服务器
		string internetIp = "8.8.8.8";
		return PingHost(internetIp);
	}


}


